package com.csust.automaticteach.manager.websocket;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @ClassNamewsHandShakeInterceptor
 * @Description ws请求拦截器
 * @Author钰玟
 * @Date2025/8/3 下午8:50
 * @Version 1.0
 **/
@Slf4j
@Component
public class WsHandShakeInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if(request instanceof ServletServerHttpRequest){
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            String requestURI = servletRequest.getRequestURI();
            String documentId = requestURI.substring(requestURI.lastIndexOf('/')+1);
            if(StrUtil.isBlank(documentId)){
                log.error("缺少文件Id参数，拒绝握手");
                return false;
            }
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
